/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jauker.badgeview.example.view.tab;

import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.PageSlider;
import ohos.agp.components.TabList;

import com.jauker.badgeview.example.util.ResUtil;

import java.util.List;
import java.util.Optional;

public class TabListListener implements TabList.TabSelectedListener {
    private static final String TAG = TabListListener.class.getCanonicalName();
    private PageSlider pager;
    private AbilitySlice slice;
    private List<? extends TabInfo> tabViews;

    public TabListListener(AbilitySlice abilitySlice, List<? extends TabInfo> list, PageSlider pageSlider) {
        this.slice = abilitySlice;
        this.tabViews = list;
        this.pager = pageSlider;
    }

    public void onSelected(TabList.Tab tab) {
        if (tab == null) {
            return;
        }
        PageSlider pageSlider = pager;
        if (pageSlider != null) {
            pageSlider.setCurrentPage(tab.getPosition());
        }
        Optional<TabInfo> associateTabView = getAssociateTabView(tab);
        if (associateTabView.isPresent()) {
            if(associateTabView.get().getIconIdSelected() != 0) {
                ResUtil.createTabIcon(slice, tab, associateTabView.get().getIconIdSelected());
            }
        }
    }

    public void onUnselected(TabList.Tab tab) {
        if (tab == null) {
            return;
        }
        Optional<TabInfo> associateTabView = getAssociateTabView(tab);
        if (associateTabView.isPresent()) {
            if(associateTabView.get().getIconId() != 0){
                ResUtil.createTabIcon(slice, tab, associateTabView.get().getIconId());
            }
        }
    }

    private Optional<TabInfo> getAssociateTabView(TabList.Tab tab) {
        int position = tab.getPosition();
        if (position >= 0 && position <= tabViews.size()) {
            return Optional.ofNullable((TabInfo) tabViews.get(position));
        }
        return Optional.empty();
    }

    public void onReselected(TabList.Tab tab) {
    }
}